#include "app.h"



#define HEAD1 0x20
#define HEAD2 0x40

uint16_t channel[IBUS_USER_CHANNELS];

// 0 左右平移
// 1 前进 后退
// 2 油门
// 3 方向偏航


typedef struct{ 
	uint8_t head1;		
	uint8_t head2;		
	uint8_t data[28];	// 数据
	uint16_t checksum; // 校验
}PROTO_T;




void app_comm_task(void)
{
    int i,j;
    uint8_t	status = 0;
    uint8_t buf[100];
    uint8_t ucCount=0;
    PROTO_T rxbuf;
    uint16_t channel_buffer[IBUS_MAX_CHANNLES] = {0};
    
    uint16_t checksum_cal;

    // 先判断接收的数据是否 大于等于 协议的长度
    if(comGetRxCount(COM1) >= sizeof(PROTO_T))
	{
        while(1)
        {
            switch (status)
            {
                case 0:
                    // 读出第一个字节
                    comGetChar(COM1,&buf[0]);
                    if(buf[0] == HEAD1) // 帧头
                    {
                        status = 1;
                        ucCount++; 
                        continue;
                    }
                    break;
                case 1:
                    // 读出第二个字节
                    comGetChar(COM1,&buf[1]);
                    if(buf[1] == HEAD2) // 帧头
                    {
                        status = 2;
                        ucCount++; 
                        continue;
                    }
                    else
                    {
                        status = 0;
                    }
                    break;
                case 2:
                    if(ucCount == sizeof(PROTO_T))
                    {

                        // 接收数据处理参考 https://blog.csdn.net/m0_51220742/article/details/123791062
                        memcpy(&rxbuf,buf,sizeof(PROTO_T));
                        checksum_cal = 0xffff - HEAD1 - HEAD2;

                        for(i = 0; i < IBUS_MAX_CHANNLES; i++)
                        {
                            channel_buffer[i] = (uint16_t)(rxbuf.data[i * 2 + 1] << 8 | rxbuf.data[i * 2 + 0]);
                            checksum_cal = checksum_cal - rxbuf.data[i * 2 + 1] - rxbuf.data[i * 2 + 0];
                        }

                        if(checksum_cal == rxbuf.checksum)
                        {
                            for(j = 0; j < IBUS_USER_CHANNELS; j++)
                            {
                                channel[j] = channel_buffer[j];
                            }
                        }
                        return;
                    }
                    else
                    {
                        if(comGetChar(COM1,&buf[ucCount++]) == 0)
                        {	
                            return;
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }
}








